package com.feeyo.groundservice.recordnfc.activity.view

import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.ActivityUtils
import com.feeyo.groundservice.base_util.CallbackWithData
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.dealString
import com.feeyo.groundservice.base_util.getConfirmDlg
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.composewidget.util.EmptyListView
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.drawableToPainter
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.button.CustomButton
import com.feeyo.groundservice.composewidget.view.edit.RoundedCornerOutlinedTextField
import com.feeyo.groundservice.composewidget.view.util.HorizontalSpace
import com.feeyo.groundservice.composewidget.view.util.VerticalSpace
import com.feeyo.groundservice.recordnfc.R
import com.feeyo.groundservice.recordnfc.constant.ResourceType
import com.feeyo.groundservice.recordnfc.constant.resumeGateCheck
import com.feeyo.groundservice.recordnfc.constant.resumeParkingCheck
import com.feeyo.groundservice.recordnfc.constant.resumeTaskCheck
import com.feeyo.groundservice.recordnfc.constant.statusBarColor
import com.feeyo.groundservice.recordnfc.constant.unitList
import com.feeyo.groundservice.recordnfc.model.GateItemBO
import com.feeyo.groundservice.recordnfc.model.NfcCarBO
import com.feeyo.groundservice.recordnfc.model.NfcUserBO
import com.feeyo.groundservice.recordnfc.model.ParkingItemBO
import com.feeyo.groundservice.recordnfc.model.TaskItemBO
import com.feeyo.groundservice.recordnfc.model.UnitItemBO
import com.feeyo.groundservice.recordnfc.viewmodel.RecorderCardViewModel
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback

/**
 *作者：70893 on 2025-10-08
 *描述：
 */

@Composable
internal fun ResourceListMainView(
    searchKey: MutableState<String>,
    resourceType: ResourceType?,
    multiSelect: Boolean,
    oldData: List<String>,//旧数据
    filterTask: List<String>,//需要过滤的数据
    listener: CallbackWithData<Any>?,//回调选择的数据
    onDismiss: () -> Unit
) {
    val mContext = LocalContext.current
    val viewModel: RecorderCardViewModel = viewModel(mContext as AppCompatActivity)
    val units = unitList.filter {
        if (resourceType != ResourceType.TASK)
            it.id.isNotEmpty()//去掉全部选项
        else
            true
    }

    val expand = remember { mutableStateOf(false) }
    val selectUnit = remember { mutableStateOf<UnitItemBO?>(null) }
    val rotate = if (expand.value) 90f else 0f

    Column(
        modifier = Modifier.fillMaxSize().background(
            color = R.color.white.toComposeColor(),
            shape = RoundedCornerShape(R.dimen.d8.dimenToDp())
        ).padding(R.dimen.d15.dimenToDp())
    ) {
        Text(
            text = resourceType?.title.dealString(),
            fontSize = R.dimen.d15.dimenToSp(),
            fontWeight = FontWeight.W500,
            color = R.color.black_33.toComposeColor(),
            modifier = Modifier.align(Alignment.CenterHorizontally)
        )
        VerticalSpace(R.dimen.d10.dimenToDp())

        val searchHint = when (resourceType) {
            ResourceType.PERSON -> "请输入姓名、工号"

            ResourceType.CAR -> "请输入车牌号"

            ResourceType.TASK -> "请输入任务名称"

            ResourceType.GATE -> "请输入登机口名称"

            ResourceType.PARKING -> "请输入机位名称"

            else -> "请输入关键词搜索"
        }
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            RoundedCornerOutlinedTextField(
                modifier = Modifier.weight(1f).height(R.dimen.d36.dimenToDp()),
                onValueChange = {
                    searchKey.value = it
                },
                cornerRadius = R.dimen.d22.dimenToDp(),
                focusedContainerColor = R.color.white.toComposeColor(),
                unfocusedContainerColor = R.color.white.toComposeColor(),
                hint = searchHint,
                cursorColor = statusBarColor.toComposeColor(),
                hasLeadingIcon = true,
                horizontalPadding = R.dimen.d10.dimenToDp()
            )

            HorizontalSpace(R.dimen.d15.dimenToDp())

            //保障单位
            if (resourceType in listOf(ResourceType.TASK, ResourceType.CAR, ResourceType.PERSON)) {
                Row(
                    modifier = Modifier.intervalClick {
                        ActivityUtils.getTopActivity()?.let {

                            XPopup.Builder(it)
                                .dismissOnBackPressed(true)
                                .hasBlurBg(false)
                                .hasShadowBg(true)
                                .dismissOnTouchOutside(true)
                                .setPopupCallback(object : SimpleCallback() {
                                    override fun beforeShow(popupView: BasePopupView?) {
                                        super.beforeShow(popupView)
                                        expand.value = !expand.value
                                    }

                                    override fun onDismiss(popupView: BasePopupView?) {
                                        super.onDismiss(popupView)
                                        expand.value = !expand.value
                                    }
                                })
                                .asBottomList(
                                    "选择保障单位",
                                    units.map { it.title }.toTypedArray(),
                                ) { position, text ->
                                    selectUnit.value = units[position]
                                }.show()
                        }
                    },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = selectUnit.value?.title ?: "",
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W500,
                        color = R.color.black_33.toComposeColor()
                    )
                    HorizontalSpace(R.dimen.d5.dimenToDp())
                    Icon(
                        painter = R.drawable.icon_arrow_right.drawableToPainter(),
                        contentDescription = null,
                        modifier = Modifier.size(R.dimen.d15.dimenToDp())
                            .rotate(rotate),
                        tint = R.color.black_66.toComposeColor()
                    )
                }
            }
        }

        VerticalSpace(R.dimen.d10.dimenToDp())

        when (resourceType) {
            ResourceType.PERSON -> UserListView(
                list = viewModel.userList.value,
                listener = listener,
                onDismiss = onDismiss
            )

            ResourceType.CAR -> CarListView(
                list = viewModel.carList.value,
                listener = listener,
                onDismiss = onDismiss
            )

            ResourceType.TASK -> TaskListView(
                multiSelect = multiSelect,
                list = viewModel.taskList.value?.filter { it.task_config.id !in filterTask },
                listener = listener,
                onDismiss = onDismiss
            )

            ResourceType.GATE -> GateListView(
                multiSelect = multiSelect,
                list = viewModel.gateList.value,
                listener = listener,
                onDismiss = onDismiss
            )

            ResourceType.PARKING -> ParkingListView(
                multiSelect = multiSelect,
                list = viewModel.parkingList.value,
                listener = listener,
                onDismiss = onDismiss
            )

            else -> {}
        }
    }

    LaunchedEffect(key1 = searchKey.value, key2 = selectUnit.value) {
        when (resourceType) {
            ResourceType.PERSON -> {
                selectUnit.value?.id?.let {
                    viewModel.getUserList(searchKey.value, it)
                }

            }

            ResourceType.CAR -> {
                selectUnit.value?.id?.let { viewModel.getCarList(searchKey.value, it) }

            }

            ResourceType.TASK -> {
                selectUnit.value?.id?.let {
                    viewModel.getTaskList(searchKey.value, it, oldData)
                }
            }

            ResourceType.GATE -> {
                //无需保障单位，全局共享的
                viewModel.getGateList(searchKey.value)
            }

            ResourceType.PARKING -> {
                //无需保障单位，全局共享的
                viewModel.getParkingList(searchKey.value)
            }


            else -> {}
        }
    }

    LaunchedEffect(Unit) {
        selectUnit.value = units.firstOrNull()
    }
}

@Composable
internal fun ColumnScope.UserListView(
    list: List<NfcUserBO>?,
    listener: CallbackWithData<Any>?,
    onDismiss: () -> Unit
) {

    list?.let { users ->
        if (users.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor()),
                contentAlignment = Alignment.Center
            ) {
                EmptyListView()
            }
        } else
            LazyColumn(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor())
            ) {
                itemsIndexed(users, key = { index, it -> it.uid }) { index, it ->
                    Box(
                        modifier = Modifier.fillMaxWidth().height(R.dimen.d30.dimenToDp())
                            .intervalClick {
                                //如果已经有卡了，弹框二次确认一下
                                if (!it.nfc.isNullOrEmpty()) {
                                    getConfirmDlg(
                                        "", "已经绑定过NFC了，确定重新绑定吗?",
                                        dismissOnBackPressed = false, dismissOnTouchOutside = false,
                                        confirmListener = object : SuccessCallback {
                                            override fun success() {
                                                super.success()
                                                listener?.success(it)
                                                onDismiss()
                                            }
                                        })?.show()
                                } else {
                                    listener?.success(it)
                                    onDismiss()
                                }


                            },
                        contentAlignment = Alignment.CenterStart
                    ) {
                        val title =
                            if (it.nfc.isNullOrEmpty()) it.truename.dealString() else "${it.truename.dealString()} | ${it.nfc}"
                        Text(
                            text = title,
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W500,
                            color = if (it.nfc.isNullOrEmpty()) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor()
                        )
                    }

                    if (index != users.size - 1) {
                        HorizontalDivider(
                            modifier = Modifier.fillMaxWidth(),
                            thickness = R.dimen.d1.dimenToDp(),
                            color = R.color.gray_DD.toComposeColor()
                        )
                    }
                }
            }
    }

}

@Composable
internal fun ColumnScope.CarListView(
    list: List<NfcCarBO>?,
    listener: CallbackWithData<Any>?,
    onDismiss: () -> Unit
) {
    list?.let { cars ->
        if (cars.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor()),
                contentAlignment = Alignment.Center
            ) {
                EmptyListView()
            }
        } else
            LazyColumn(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor())
            ) {
                itemsIndexed(cars, key = { index, it -> it.id }) { index, it ->
                    Box(
                        modifier = Modifier.fillMaxWidth().height(R.dimen.d30.dimenToDp())
                            .padding(horizontal = R.dimen.d10.dimenToDp())
                            .intervalClick {
                                //如果已经有卡了，弹框二次确认一下
                                if (!it.nfcs.isNullOrEmpty()) {
                                    getConfirmDlg(
                                        "", "已经绑定过NFC了，确定重新绑定吗?",
                                        dismissOnBackPressed = false, dismissOnTouchOutside = false,
                                        confirmListener = object : SuccessCallback {
                                            override fun success() {
                                                super.success()
                                                listener?.success(it)
                                                onDismiss()
                                            }
                                        })?.show()
                                } else {
                                    listener?.success(it)
                                    onDismiss()
                                }

                            },
                        contentAlignment = Alignment.CenterStart
                    ) {
                        val title =
                            if (it.nfcs.isNullOrEmpty()) it.title.dealString() else "${it.title.dealString()} | ${it.nfcs}"
                        Text(
                            text = title,
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W500,
                            color = if (it.nfcs.isNullOrEmpty()) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor()
                        )
                    }

                    if (index != cars.size - 1) {
                        HorizontalDivider(
                            modifier = Modifier.fillMaxWidth(),
                            thickness = R.dimen.d1.dimenToDp(),
                            color = R.color.gray_DD.toComposeColor()
                        )
                    }
                }
            }
    }

}

@Composable
@Stable
internal fun ColumnScope.TaskListView(
    multiSelect: Boolean,
    list: List<TaskItemBO>?,
    listener: CallbackWithData<Any>?,
    onDismiss: () -> Unit
) {
    val itemSpace = R.dimen.d10.dimenToDp()
    val isCheckAll = remember(list) { mutableStateOf(false) }

    list?.let { tasks ->
        if (tasks.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor()),
                contentAlignment = Alignment.Center
            ) {
                EmptyListView()
            }
        } else {
            //是否全选
            isCheckAll.value = tasks.all { it.task_config.checked.value }
            //全选 取消全选
            val iconColor = if (isCheckAll.value)
                statusBarColor.toComposeColor()
            else
                R.color.black_66.toComposeColor()

            Row(
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Checkbox(
                    checked = isCheckAll.value,
                    onCheckedChange = {
                        isCheckAll.value = it
                        tasks.forEach { task ->
                            task.task_config.checked.value = it
                        }
                    },
                    colors = CheckboxDefaults.colors().copy(
                        checkedCheckmarkColor = R.color.white.toComposeColor(),
                        uncheckedCheckmarkColor = R.color.white.toComposeColor(),
                        checkedBoxColor = statusBarColor.toComposeColor(),
                        uncheckedBoxColor = R.color.white.toComposeColor(),
                        checkedBorderColor = statusBarColor.toComposeColor(),
                        uncheckedBorderColor = R.color.black_66.toComposeColor()
                    ),
                    modifier = Modifier.size(R.dimen.d24.dimenToDp())
                )

                HorizontalSpace(R.dimen.d5.dimenToDp())
                Text(
                    text = "全选",
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W500,
                    color = iconColor
                )
            }
            LazyVerticalGrid(
                columns = GridCells.Fixed(count = 3),
                modifier = Modifier.background(R.color.white.toComposeColor())
                    .padding(vertical = R.dimen.d12.dimenToDp())
                    .fillMaxWidth().weight(1f),
                horizontalArrangement = Arrangement.spacedBy(itemSpace),
                verticalArrangement = Arrangement.spacedBy(itemSpace)
            ) {
                items(tasks, key = { it.task_config.id }) {

                    val bg = animateColorAsState(
                        targetValue = if (it.task_config.checked.value)
                            statusBarColor.toComposeColor()
                        else
                            R.color.gray_EA.toComposeColor()
                    )

                    val textColor = animateColorAsState(
                        targetValue = if (it.task_config.checked.value)
                            R.color.white.toComposeColor()
                        else
                            R.color.black_33.toComposeColor()
                    )

                    Box(
                        modifier = Modifier.fillMaxWidth().height(R.dimen.d36.dimenToDp())
                            .background(
                                color = bg.value,
                                shape = RoundedCornerShape(R.dimen.d5.dimenToDp())
                            ).padding(horizontal = R.dimen.d3.dimenToDp())
                            .intervalClick {
                                if (multiSelect) {
                                    it.task_config.checked.value = !it.task_config.checked.value
                                    //是否全部选中了
                                    if (tasks.all { it.task_config.checked.value }) {
                                        isCheckAll.value = true
                                    } else {
                                        isCheckAll.value = false
                                    }
                                } else {
                                    if (!it.task_config.checked.value) {
                                        tasks.resumeTaskCheck()
                                        it.task_config.checked.value = true
                                    }
                                }
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = it.task_config.title.dealString(),
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W500,
                            color = textColor.value
                        )
                    }
                }
            }

            SubmitButton(
                onSubmit = {
                    tasks.filter { it.task_config.checked.value }.apply {
                        if (isNotEmpty()) {
                            listener?.success(this)
                            onDismiss()
                        } else {
                            toastCenter("请至少选择一个")
                        }
                    }
                }
            )
        }
    }
}

@Composable
internal fun ColumnScope.ParkingListView(
    multiSelect: Boolean,
    list: List<ParkingItemBO>?,
    listener: CallbackWithData<Any>?,
    onDismiss: () -> Unit,
) {

    val itemSpace = R.dimen.d10.dimenToDp()

    list?.let { parking ->
        if (parking.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor()),
                contentAlignment = Alignment.Center
            ) {
                EmptyListView()
            }
        } else {
            LazyVerticalGrid(
                columns = GridCells.Fixed(count = 3),
                modifier = Modifier.background(R.color.white.toComposeColor())
                    .padding(vertical = R.dimen.d12.dimenToDp())
                    .fillMaxWidth().weight(1f),
                horizontalArrangement = Arrangement.spacedBy(itemSpace),
                verticalArrangement = Arrangement.spacedBy(itemSpace)
            ) {
                items(parking, key = { it.id }) {

                    val bg = animateColorAsState(
                        targetValue = if (it.checked.value)
                            statusBarColor.toComposeColor()
                        else
                            R.color.gray_EA.toComposeColor()
                    )

                    val textColor = animateColorAsState(
                        targetValue = if (it.checked.value)
                            R.color.white.toComposeColor()
                        else
                            R.color.black_33.toComposeColor()
                    )

                    Box(
                        modifier = Modifier.fillMaxWidth().height(R.dimen.d30.dimenToDp())
                            .background(
                                color = bg.value,
                                shape = RoundedCornerShape(R.dimen.d5.dimenToDp())
                            ).intervalClick {
                                if (multiSelect) {
                                    it.checked.value = !it.checked.value
                                } else {
                                    if (!it.checked.value) {
                                        parking.resumeParkingCheck()
                                        it.checked.value = true
                                    }
                                }
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = it.title.dealString(),
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W500,
                            color = textColor.value
                        )
                    }
                }
            }

            SubmitButton(
                onSubmit = {
                    parking.filter { it.checked.value }.firstOrNull()?.let {
                        listener?.success(it)
                        onDismiss()
                    } ?: toastCenter("请选择一个机位")
                }
            )
        }
    }
}

@Composable
internal fun ColumnScope.GateListView(
    multiSelect: Boolean,
    list: List<GateItemBO>?,
    listener: CallbackWithData<Any>?,
    onDismiss: () -> Unit
) {
    val itemSpace = R.dimen.d10.dimenToDp()

    list?.let { gate ->
        if (gate.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxWidth().weight(1f)
                    .background(R.color.white.toComposeColor()),
                contentAlignment = Alignment.Center
            ) {
                EmptyListView()
            }
        } else {
            LazyVerticalGrid(
                columns = GridCells.Fixed(count = 3),
                modifier = Modifier.background(R.color.white.toComposeColor())
                    .padding(vertical = R.dimen.d12.dimenToDp())
                    .fillMaxWidth().weight(1f),
                horizontalArrangement = Arrangement.spacedBy(itemSpace),
                verticalArrangement = Arrangement.spacedBy(itemSpace)
            ) {
                items(gate, key = { it.id }) {

                    val bg = animateColorAsState(
                        targetValue = if (it.checked.value)
                            statusBarColor.toComposeColor()
                        else
                            R.color.gray_EA.toComposeColor()
                    )

                    val textColor = animateColorAsState(
                        targetValue = if (it.checked.value)
                            R.color.white.toComposeColor()
                        else
                            R.color.black_33.toComposeColor()
                    )

                    Box(
                        modifier = Modifier.fillMaxWidth().height(R.dimen.d30.dimenToDp())
                            .background(
                                color = bg.value,
                                shape = RoundedCornerShape(R.dimen.d5.dimenToDp())
                            ).intervalClick {
                                if (multiSelect) {
                                    it.checked.value = !it.checked.value
                                } else {
                                    if (!it.checked.value) {
                                        gate.resumeGateCheck()
                                        it.checked.value = true
                                    }
                                }
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = it.title.dealString(),
                            fontSize = R.dimen.d14.dimenToSp(),
                            fontWeight = FontWeight.W500,
                            color = textColor.value
                        )
                    }
                }
            }

            SubmitButton(
                onSubmit = {
                    gate.filter { it.checked.value }.firstOrNull()?.let {
                        listener?.success(it)
                        onDismiss()
                    } ?: toastCenter("请选择一个登机口")
                }
            )

        }
    }
}


@Composable
private fun SubmitButton(
    onSubmit: () -> Unit
) {
    Box(
        modifier = Modifier.fillMaxWidth().padding(horizontal = R.dimen.d15.dimenToDp())
    ) {
        CustomButton(
            modifier = Modifier.fillMaxWidth().height(R.dimen.d36.dimenToDp()),
            bgs = listOf(
                statusBarColor.toComposeColor(),
                statusBarColor.toComposeColor().copy(0.8f)
            ),
            cornerShape = RoundedCornerShape(R.dimen.d5.dimenToDp()),
            onClick = { onSubmit() }
        ) {
            Text(
                text = "选好了",
                fontSize = R.dimen.d14.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = R.color.white.toComposeColor(),
                modifier = Modifier.align(Alignment.Center)
            )
        }
    }
}
